import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class WebSocketService {

  ws: WebSocket;

  constructor() {
  }

  createObeservableSocket(url: string): Observable<any> {
    this.ws = new WebSocket(url);
    return new Observable(
      observer => {
        /*当接收到消息是，发射一个元素 (event)传递过来的数据*/
        this.ws.onmessage = (event) => observer.next(event.data);
        /*当这个webSocket发生错误时，流跑出一个异常*/
        this.ws.onerror = (event) => observer.error(event);
        /*当这个webSocket关闭.结束*/
        this.ws.onclose = (event) => observer.complete();
      }
    );
  }

  sendMessage(message: string) {
    this.ws.send(message);
  }
}
